//
//  ASColListController.swift
//  soapp
//
//  Created by zhu xietong on 2018/4/24.
//

import Foundation
import Kingfisher
import Eelay
import JoLoading
import AsyncDisplayKit




open class ASColListController: TypeInitController,ASCollectionVConfig,ASCollectionDelegateFlowLayout{
   
    
    
    
//    public var collectionNode:ASCollectionNode!
    open var collectionView:UICollectionView{
        get{
            return collectionNode.view
        }
    }
    
    public var so_constrains = [NSLayoutConstraint]()
    public var edegs:(top:CGFloat,left:CGFloat,bottom:CGFloat,right:CGFloat) = (0,0,0,0)
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    public var flowLayout = UICollectionViewFlowLayout()

    
    public lazy var collectionNode:ASCollectionNode={
        self.flowLayout = UICollectionViewFlowLayout()
        let collectionNode = ASCollectionNode(collectionViewLayout: flowLayout)
        return collectionNode
    }()
    
    required public init() {
        flowLayout = UICollectionViewFlowLayout()
//        collectionNode = ASCollectionNode(collectionViewLayout: flowLayout)
        super.init()
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
//        let w = Swidth/2.0 - 10
//        flowLayout.itemSize = CGSize(width: w, height: w)
       
    }
    
    public var page_load_section = "section0"
    
    public var sectionIndex:Int{
        get{
            let s = self.page_load_section.replacingOccurrences(of: "section", with: "")
            return Int(s) ?? 0
        }
    }
    
    
    
    public func load(sections:TP.section,selector:TP.selector)
    {
        collectionNode.load(sections: sections, selector: selector)
    }
    
    public var contentInsetView: UIScrollView? {
        get{
            return self.collectionView
        }
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        flowLayout.sectionHeadersPinToVisibleBounds = true
        flowLayout.minimumLineSpacing = 0
        //        flowLayout.headerReferenceSize = [Swidth,30]
        collectionNode.registerSupplementaryNode(ofKind: UICollectionView.elementKindSectionHeader)
        self.view.backgroundColor = UIColor.white
        collectionNode.alwaysBounceVertical = true

        layCollection(collectionView: collectionView)
        configCollections(nodes: collectionNode)
        
        
    }
    
    open func layCollection(collectionView:UIView)
    {
        jo_contentView.eelay = [
            [collectionView,[ee.T.L.B.R]]
        ]
    }
    
    
    public func remove_constains()
    {
        self.jo_contentView.removeConstraints(self.so_constrains)
    }
    
    open func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        TypeInitController.IDActiveAction(self,actionID,model)
    }
    
    
    open func reloadDataActionHappensHere(){
        let count = collectionNode.dataSource?.collectionNode?(collectionNode, numberOfItemsInSection: 0) ?? 0
        if count > 2 {
            for row in 0...(count-1)
            {
                indexPathesToBeReloaded.append(IndexPath(row:row,section:0))
            }
        }
        self.collectionNode.reloadData()
        collectionNode.waitUntilAllUpdatesAreProcessed();
        
    }
    public var indexPathesToBeReloaded: [IndexPath] = []
    
    open func checkCell(cell:ASCellNode,indexPath: IndexPath) {
        
    }
    
    open func collectionNode(_ collectionNode: ASCollectionNode, didSelectItemAt indexPath: IndexPath) {
        
        if let cell = collectionNode.nodeForItem(at: indexPath) as? JoCellNode{
            if let action = cell.mo.model["@click"] as? _Click{
                action.block(self)
                return
            }
            
            if let action = mo.model["@click"] as? _KitClick<Self>{
                if let obj = self as? Self{
                    action.block(obj)
                    return
                }
            }
            cell.didSelect(at: indexPath)
        }
        
    }
    
    open func collectionNode(_ collectionNode: ASCollectionNode, nodeForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> ASCellNode {
        let n = collectionNode.headerNode(section: indexPath.section,fillModel: true,delegate: self)
//        print(")_))S))S",n)
        return n
 
    }
    

    open func collectionNode(_ collectionNode: ASCollectionNode, nodeForItemAt indexPath: IndexPath) -> ASCellNode {

        let cell = collectionNode.cellNode(indexPath: indexPath, fillModel: true, delegate: self)
        cell.neverShowPlaceholders = true
        if let cnode = cell as? JoCellNode
        {
        
            cnode.delegate = self
        
        }
//        checkCell(cell: cell, indexPath: indexPath)
//        if indexPathesToBeReloaded.contains(indexPath) {
//            let oldCellNode = collectionNode.nodeForItem(at: indexPath)
//            cell.neverShowPlaceholders = true
//            oldCellNode?.neverShowPlaceholders = true
//            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
//                cell.neverShowPlaceholders = false
//                if let indexP = self.indexPathesToBeReloaded.firstIndex(of: indexPath) {
//                    self.indexPathesToBeReloaded.remove(at: indexP)
//                }
//            })
//        }
        return cell
    }
    
    
  
    public func collectionView(_ collectionView: ASCollectionView, constrainedSizeForNodeAt indexPath: IndexPath) -> ASSizeRange {
        let size = ASSizeRange.collectionNode(collectionNode: collectionNode, indexPath: indexPath,controller: self)
        return size
    }

    public func collectionNode(_ collectionNode: ASCollectionNode, willDisplayItemWith node: ASCellNode) {
        (node as? JoCellNode)?.mo_will_display()

    }
    public func collectionNode(_ collectionNode: ASCollectionNode, didEndDisplayingItemWith node: ASCellNode) {
        (node as? JoCellNode)?.mo_end_display()
    }
    
    
//    open func collectionNode(_ collectionNode: ASCollectionNode, nodeForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> ASCellNode {
//        print("++++++++____S____S_S")
//        let head = collectionNode.headerNode(section: indexPath.section, fillModel: true, delegate: self)
//
//        if let cnode = head as? JoCellNode
//        {
//            cnode.delegate = self
//        }
//        return head
//    }
    
    open func collectionNode(_ collectionNode: ASCollectionNode, sizeRangeForHeaderInSection section: Int) -> ASSizeRange {
        
        return collectionNode.headerSize(section: section, fillModel: true, delegate: self)
//        return collectionNode.headerSize(section: section)
    }
    
//    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
//        
//    }
    
    override open func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    deinit {

        KingfisherManager.shared.cache.clearMemoryCache()
    }
    
    
    
    
}

